package com.ytsky.hctechnologysys.controller;



import com.ytsky.hctechnologysys.entity.Employee;
import com.ytsky.hctechnologysys.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

/**
 * @author Dell
 */
@Controller
public class LoginController {


    @Autowired
    private EmployeeService employeeService;

    @GetMapping("/login")
    public ModelAndView loginView(){
        ModelAndView mav = new ModelAndView("login");
        return mav;
    }

    @PostMapping("/login")
    public ModelAndView login(
            @RequestParam(name = "username", required = true, defaultValue = "") String username,
            @RequestParam(name = "password", required = true, defaultValue = "") String password,
            HttpSession session
    ){
        ModelAndView mav = new ModelAndView("redirect:/index");

        Employee user  = employeeService.findByNamePass(username,password);
        if(user != null){
            //如果登录用户存在，则登录成功 然后 将该用户的信息保存在会话对象中  以便在整个操作过程中  都能够访问到用户信息
            session.setAttribute("user",user);
        }else{

            mav.setViewName("redirect:/login");
        }
        return mav;
    }

    @GetMapping("/logout")
    public ModelAndView logout(HttpSession session, SessionStatus sessionStatus){
        ModelAndView mav = new ModelAndView("redirect:logout");
        // 退出登录：核心是要清空当前会话的会话对象 并将会话对象框作废
        session.removeAttribute("user");
        session.invalidate();
        // 调用了
        sessionStatus.setComplete();
        return mav;
    }


}
